#!/bin/bash

# 测试MySQL删除功能的脚本
# 使用方法：./test-mysql-delete.sh <container_name> <db_name> <username>

if [ $# -ne 3 ]; then
    echo "使用方法: $0 <container_name> <db_name> <username>"
    echo "示例: $0 mysql-shared-test test_db test_user"
    exit 1
fi

CONTAINER_NAME=$1
DB_NAME=$2
USERNAME=$3

echo "测试删除MySQL资源..."
echo "容器名称: $CONTAINER_NAME"
echo "数据库名称: $DB_NAME"
echo "用户名: $USERNAME"
echo ""

# 检查容器是否存在
if ! docker ps | grep -q "$CONTAINER_NAME"; then
    echo "错误: 容器 $CONTAINER_NAME 不存在或未运行"
    exit 1
fi

echo "1. 检查容器状态..."
docker ps | grep "$CONTAINER_NAME"

echo ""
echo "2. 检查数据库是否存在..."
docker exec "$CONTAINER_NAME" mysql -uroot -p123456 -e "SHOW DATABASES LIKE '$DB_NAME';"

echo ""
echo "3. 检查用户是否存在..."
docker exec "$CONTAINER_NAME" mysql -uroot -p123456 -e "SELECT User, Host FROM mysql.user WHERE User='$USERNAME';"

echo ""
echo "4. 执行删除操作..."

# 删除数据库
echo "删除数据库 $DB_NAME..."
docker exec "$CONTAINER_NAME" mysql -uroot -p123456 -e "DROP DATABASE IF EXISTS \`$DB_NAME\`;"

# 删除用户
echo "删除用户 $USERNAME..."
docker exec "$CONTAINER_NAME" mysql -uroot -p123456 -e "DROP USER IF EXISTS '$USERNAME'@'%';"

# 刷新权限
echo "刷新权限..."
docker exec "$CONTAINER_NAME" mysql -uroot -p123456 -e "FLUSH PRIVILEGES;"

echo ""
echo "5. 验证删除结果..."

echo "检查数据库是否已删除..."
docker exec "$CONTAINER_NAME" mysql -uroot -p123456 -e "SHOW DATABASES LIKE '$DB_NAME';"

echo "检查用户是否已删除..."
docker exec "$CONTAINER_NAME" mysql -uroot -p123456 -e "SELECT User, Host FROM mysql.user WHERE User='$USERNAME';"

echo ""
echo "测试完成！" 